﻿using StoryTeller.Domain;
using StoryTeller.Domain.Exceptions;
using StoryTeller.Domain.Repository;
using StoryTeller.Infrastructure.DataAccess.DAL;
using StoryTeller.Infrastructure.DataAccess.DAL.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StoryTeller.Repository
{
    public class UserRepository : BaseRepository<User>, IUserRepository
    {
        public IUserDAL dal { get { return DALFactory.GetUserDAL(); } }

        public void Insert(User entidade)
        {
            try
            {
                if (entidade.Validate())
                    throw new ValidationMessagesException(entidade.ValidationMessages);

                dal.Insert(entidade);
            }
            catch (ValidationMessagesException ex)
            {
                throw ex;
            }            
            catch (Exception ex)
            {
                throw new FriendlyErrorMessageException(Resources.Error.ErrorMessages.UserInsertError, ex);
            }
        }

        public void Update(User entidade)
        {
            try
            {
                if (entidade.Validate())
                    throw new ValidationMessagesException(entidade.ValidationMessages);

                dal.Update(entidade);
            }
            catch (ValidationMessagesException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw new FriendlyErrorMessageException(Resources.Error.ErrorMessages.UserUpdateError, ex);
            }
        }

        public void Delete(int id)
        {
            try
            {
                dal.Delete(id);
            }
            catch (Exception ex)
            {
                throw new FriendlyErrorMessageException(Resources.Error.ErrorMessages.UserDeleteError, ex);
            }
        }

        public ICollection<User> Select()
        {
            try
            {
                return dal.Select();
            }
            catch (Exception ex)
            {
                throw new FriendlyErrorMessageException(Resources.Error.ErrorMessages.UserSelectAllError, ex);
            }
        }

        public User Select(int id)
        {
            try
            {
                return dal.Select(id);
            }
            catch (Exception ex)
            {
                throw new FriendlyErrorMessageException(Resources.Error.ErrorMessages.UserSelectByIdError, ex);
            }
        }

        public User Login(string usrProviderId)
        {
            try
            {
                return dal.Select(usrProviderId);
            }
            catch (Exception ex)
            {
                throw new FriendlyErrorMessageException(Resources.Error.ErrorMessages.UserLoginError, ex);
            }
        }
    }
}
